package eu.jba.denshijisho;

import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import eu.jba.denshijisho.dao.CardDao;
import eu.jba.denshijisho.entity.Card;
import eu.jba.denshijisho.exceptionhandler.ExceptionHandler;
import eu.jba.denshijisho.listeners.ListenersHelper;
import eu.jba.denshijisho.util.Constants;

public class EditCardActivity extends AbstractDenshiActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Thread.setDefaultUncaughtExceptionHandler( new ExceptionHandler( this ));
		setContentView(R.layout.activity_edit_card);
		setFinishOnTouchOutside(false);
		final Bundle bundle = getIntent().getExtras();
		final Card card = (Card)bundle.getSerializable(Constants.CARD);
		((EditText) findViewById(R.id.svk_lang_text_field_edit)).setText( card.getSvkWord() );
		((EditText) findViewById(R.id.kana_text_field_edit)).setText( card.getKanaWord() );
		((EditText) findViewById(R.id.kanji_text_field_edit)).setText( card.getKanji() );		
		final Spinner spinner = (Spinner) findViewById(R.id.word_phrase_spinner_edit);
		final ArrayAdapter<CharSequence> adapter = ArrayAdapter
				.createFromResource(this, R.array.word_phrase,
						R.layout.dropdown_item);
		adapter.setDropDownViewResource(R.layout.dropdown_item);
		spinner.setAdapter(adapter);
		final int spinnerPosition = adapter.getPosition(card.getType());
		spinner.setSelection(spinnerPosition);
		spinner.setOnItemSelectedListener( ListenersHelper.getSelectType() );
	}

	public void closeDialog(View view) {
		setResult(RESULT_CANCELED);
		finish();
	}

	public void updateCard(View view) {
		final String svkLang = ((EditText) findViewById(R.id.svk_lang_text_field_edit))
				.getText().toString();
		final String kana = ((EditText) findViewById(R.id.kana_text_field_edit))
				.getText().toString();
		final String kanji = ((EditText) findViewById(R.id.kanji_text_field_edit))
				.getText().toString();
		final String type = ListenersHelper.getSelectedType();
		final Bundle bundle = getIntent().getExtras();
		final Card card = (Card)bundle.getSerializable(Constants.CARD);
		
		card.setSvkWord(svkLang);
		card.setKanaWord(kana);
		card.setKanji(kanji);
		card.setType(type);
		
		final CardDao databaseAdapter = new CardDao(this);
		databaseAdapter.open();
		databaseAdapter.update(card);
		databaseAdapter.close();
		setResult(RESULT_OK);
		finish();
	}
}
